<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>

<body>
    <form>
        <table align="center">
            <caption>
                <h2>登录</h2>
            </caption>
            <tr>
                <td>用户名：</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码：</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="reset">
                    <input type="submit">
                </td>
            </tr>
        </table>
    </form>
</body>
<script src="./js/requset.js"></script>
<script src="./js/cookie.js"></script>
<script>
    var form = document.querySelector('form')
    form.onsubmit = function (event) {
        event.preventDefault()
        var username = document.querySelector('[name="username"]').value
        var password = document.querySelector('[name="password"]').value
        var usernameReg = /^[a-zA-Z][a-zA-Z0-9]{3,9}$/
        if (!usernameReg.test(username)) {
            alert('用户名不符合规则')
            return false
        }
        var passwordReg = /^.{6,10}$/
        if (!passwordReg.test(password)) {
            alert('密码不符合规则')
            return false
        }
        // console.log(username, password);
        request({
            method: 'post',
            url: '/user/login',
            data: {
                username: username,
                password: password
            }
        }).then((res) => {
            console.log(res);
            //登录成功后跳转到登录
            if (res.error_code === 0) {
                //生成前端登录cookie
                setCookie('username', username, 3600 * 5)
                setCookie('userid', res.data.id, 3600 * 5)
                // 存储响应回的令牌
                localStorage.token = res.data.token
                //跳转到首页
                if (localStorage.getItem('url')) {
                    location.href = localStorage.getItem('url')
                    localStorage.removeItem('url')
                } else {
                    location.href = '/index.html'
                }
            } else if (res.error_code === 2) {
                alert(res.msg)
            } else if (res.error_code === 3) {
                alert(res.msg)
            }
        }).catch(() => {
            new Error('错误')
        });
        // 阻止默认行为，不允许表单跳转
        // return false
    }
</script>

</html>